import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { IntegralLog, IntegralLogDocument } from './schemas/integral-log.schema';
import { UserService } from '../user/user.service';

@Injectable()
// 积分服务
export class IntegralService {
  constructor(
    @InjectModel(IntegralLog.name) private integralLogModel: Model<IntegralLogDocument>,
    private userService: UserService,
  ) {}

  async addIntegralLog(data: {
    integralAddType: string;
    userEmail: string;
  }) {
    const { integralAddType, userEmail } = data;

    if (integralAddType === '1') {
      // Check if user has already signed in today
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const existingLog = await this.integralLogModel.findOne({
        integral_user_email: userEmail,
        integral_add_type: '1',
        createDate: { $gte: today },
      });

      if (existingLog) {
        throw new BadRequestException('You have already signed in today');
      }

      // Create integral log
      const integralLog = new this.integralLogModel({
        integral_user_email: userEmail,
        integral_type: '1',
        integral_add_type: '1',
        integral_value: 1,
        integral_reason: '签到获得+1简币',
      });

      await integralLog.save();

      // Add coins to user
      await this.userService.addCoins(userEmail, 1);

      return {
        message: '请求成功',
        data: integralLog,
        status: 200,
      };
    }

    throw new BadRequestException('Invalid integral add type');
  }
} 